var stockGroupDAO = require('../controller/controller.stockGroup');
var stockChannelDAO = require('../controller/controller.stockChannel');
var stockDealDAO = require('../controller/controller.stockDeal');
var stockPositionDAO = require('../controller/controller.stockPosition');
var async = require('async');
/**
 * 股票交易Service
 */
module.exports = {
    getList: function (req, res, next) {
        async.waterfall([
            function (done) {
                stockGroupDAO.get({'rowId': req.body.params.groupId}, function (err, result) {
                    if (err) {
                        next({'code': 404, 'message': "查询分组错误"});
                        return;
                    }
                    done(err, result.obj || null);
                });
            },
            function (stockGroup, done) {
                async.map(stockGroup.stockChannelIds, function (stockChannel, callback) {
                    stockChannelDAO.get(stockChannel, function (err, res) {
                        stockChannel.stockId = res.obj.stockId;
                        callback()
                    });

                }, function (err) {
                    done(err, stockGroup)
                })
            },
            function (stockGroup, done) {
                var ids = [];
                for (item of stockGroup.stockChannelIds) {
                    ids.push(item.rowId);
                }
                stockDealDAO.list({stockChannelIds: ids}, function (err, list) {

                    done(err, list.obj);
                });
            }, function (dealList, done) {
                async.each(dealList, function (deal, ca) {
                        stockChannelDAO.get({rowId: deal.stockChannelId.rowId}, function (err, res) {
                            deal.stockChannelId = res.obj;
                            ca();
                        });
                    }, function (err) {
                        done(err, dealList)
                    }
                )
            }
        ], function (error, result) {
            if (error) {
                console.log(error);
                next({code: 404, message: '查询错误'})
            } else {
                console.log(result);
                next(result);
            }
        });

    },

    //创建交易信息
    createOrUpdate: function (req, res, next) {
        var that = this;
        var params = req.body.params && req.body.params.deal || {};
        params.channelType = 'stockDeal';
        params.stockGroupId = params.groupId;
        params.createUid = req.session.uid;
        params.enable = 1;
        if (!params.type) {
            next({'code': 404, 'message': "缺失交易类型"});
        }
        async.waterfall([
            function (done) {//按组查询仓位
                stockPositionDAO.findByGroupId({stockGroupId: params.stockGroupId}, function (err, result) {
                    if (err) {
                        done({'code': 404, 'message': "仓位查询出错"});
                    } else {
                       done(null, result.obj);
                    }
                });
            },
            function(stockPosition,done){
                params.channelType = 'stockDeal';
                stockChannelDAO.getByStockIdAndGroupId(params,function(err,result){
                    if (err) {
                        done({'code': 404, 'message': "股票信息查询错误"});
                    }else{
                        if(params.type == 0 && !result.obj){//股票交易记录无买入，直接卖出
                            done({'code': 404, 'message': "暂未买入该股"});
                        }else{
                            done(null,{stockChannel:result.obj,stockPosition:stockPosition})
                        }
                    }
                });
            },
            function (result, done) {//创建或更新股票信息
                var stockChannel = result.stockChannel;
                var stockPosition = result.stockPosition;
                var balance = stockPosition.balance;//当前仓位总余额
                var positionPic = stockPosition.price;//当前仓位总值
                if(!stockChannel){//无股票信息
                    var channel = stockChannelDAO.initChannel(params);
                    channel.cost = params.price;
                    channel.positionNum = params.num;
                    var countPositionVal = that.countPositionVal(stockPosition,params.type,params.price,params.num,0,balance,positionPic);
                    if (countPositionVal.code == 200) {
                        stockChannelDAO.create(channel, function (err, channelRes) {
                            if (err) {
                                done({'code': 404, 'message': "股票信息创建错误"});
                            } else {
                                    stockPositionDAO.update(countPositionVal.obj, function (err, res) {
                                        if (err) {
                                            done({'code': 404, 'message': "仓位余额更新失败"});
                                        } else {
                                            done(null, {stockChannel: channelRes.obj, stockPosition: stockPosition});
                                        }
                                    });
                                }
                        });
                    }
                    else {
                        done(countPositionVal);
                    }
                }else{//存在股票信息
                    // stockDealDAO.getAllInDate({stockChannelIds: [stockChannel]}, function (err, data) {
                    //     if (err) {
                    //         done({'code': 404, 'message': "成本查询出错"})
                    //     } else {
                            var channelCost = stockChannel.cost||0;
                            var channelNum = stockChannel.positionNum;

                           async.series({
                               updatePosition:function(ca){//更新持仓

                                   var countPositionVal = that.countPositionVal(stockPosition,params.type,params.price,params.num,channelNum,balance,positionPic);

                                   if (countPositionVal.code == 200) {
                                       stockPositionDAO.update(countPositionVal.obj, function (err, res) {
                                           if (err) {
                                               ca({'code': 404, 'message': "仓位余额更新失败"});
                                           } else {
                                               ca(null, stockPosition);
                                           }
                                       });
                                   }else{
                                       done(countPositionVal);
                                   }
                               },
                               updateChannel:function(ca){//更新成本
                                   var channelVal = channelCost * channelNum;//当前成本总值

                                   if(params.type == 1){
                                       stockChannel.positionNum = parseInt(channelNum) + parseInt(params.num);
                                       channelVal = parseInt(channelVal)+ parseInt(params.num * params.price);
                                       channelNum = parseInt(channelNum) + parseInt(params.num);
                                       stockChannel.cost = (channelVal /channelNum).toFixed(2);
                                   }else{
                                       stockChannel.positionNum = channelNum - params.num;
                                       //channelVal = (channelVal- params.num * params.price)<=0?0:(channelVal- params.num * params.price);//卖出值大于买入值
                                       channelNum = channelNum - params.num;
                                       stockChannel.cost = channelNum == 0 ? 0:channelCost;//全部股数卖出，成本归零,否则还是买入时成本
                                       //if(channelVal == 0){//判断是否卖出股值大于买入股值，已经回本，剩余部分用之前的成本价
                                            //stockChannel.cost = channelCost;
                                       // }
                                   }
                                   stockChannelDAO.update(stockChannel, function (err, res) {
                                       if (err) {
                                           ca({'code': 404, 'message': "更新成本出错"});
                                       } else {
                                           ca(null, stockChannel);
                                       }
                                   })
                               }
                           },function(err,result){
                               if (err) {
                                   done(err)
                               } else {
                                   done(null, {stockChannel:result.updateChannel,stockPosition:result.updatePosition});
                               }
                           });
                        }
                    //})
                //}
            },

            function (result, done) {
                var channel = result.stockChannel;
                stockDealDAO.findLastDealByChannel({'stockChannelId': channel.rowId}, function (err, res) {
                    if (err) {
                        done({'code': 404, 'message': "查询持仓出错"});
                    } else {
                        var lastDeal = res.obj;
                        if (lastDeal && lastDeal.length > 0) {
                            channel.lastPositionRate = lastDeal[0].positionRate;
                        } else {
                            channel.lastPositionRate = 0;
                        }
                        result.stockChannel = channel;
                        done(err, result);
                    }
                });
            },
            function (result, done) {
                var channel = result.stockChannel;
                var stockPosition = result .stockPosition;
                var daoMethod = stockDealDAO[params.rowId ? 'update' : 'create'];
                params.positionRate = (params.price * params.num / stockPosition.price * 100).toFixed(2);
                var lastRate = channel.lastPositionRate == 0 ? 0 : channel.lastPositionRate.substring(channel.lastPositionRate.indexOf("-") + 1, channel.lastPositionRate.lastIndexOf("%"));
                //调仓比例计算
                if (params.type == 1) {
                    if (channel.lastPositionRate == 0) {
                        params.positionRate = '0%-' + params.positionRate + '%';
                    } else {
                        params.positionRate = lastRate + '%-' + (parseFloat(lastRate) + parseFloat(params.positionRate)) + '%';
                    }
                } else {
                    var dealRate = channel.lastPositionRate.substring(channel.lastPositionRate.indexOf("-") + 1, channel.lastPositionRate.lastIndexOf("%")) - params.positionRate;
                    params.positionRate = channel.lastPositionRate.substring(channel.lastPositionRate.indexOf("-") + 1, channel.lastPositionRate.lastIndexOf("%")) + '%-' + (dealRate < 0?0:dealRate) + '%';
                }
                params.stockChannelId = channel && channel.rowId || null;
                daoMethod(params, function (err, result) {
                    if (err) {
                        done({'code': 404, 'message': "交易保存出错"});
                    } else {
                        done(err, channel);
                    }
                });
            }

        ], function (error, result) {
            if (error) {
                console.log(error);
                next(error)
            } else {
                console.log(result);
                next({code: 200, message: '交易成功'});
            }
        });
    },
    /**
     *
     * @param stockPosition 仓位
     * @param type 买入、卖出
     * @param dealPrice 交易金额
     * @param dealNum 交易量
     * @param allNum 股票总股
     * @param balance仓位余额
     * @param allVal 仓位总值
     * @returns {*}
     */
    countPositionVal:function(stockPosition,type,dealPrice,dealNum,allNum,balance,allVal) {
        if (type == 1){//买入,仓位表余额减少
            balance = balance - dealPrice * dealNum;
        }else{//卖出，仓位余额增加
            balance = balance + dealPrice * dealNum;
            if (parseInt(allNum) >= parseInt(dealNum) ) {//卖出股数小于当前总股数
                //if(balance> allVal){//当余额+当次交易值大于总仓值 ，提升总仓值
                    //stockPosition.price = balance;//只要卖出总仓值就变化
               // }
            }else{
                return {'code': 404, 'message': "卖出量大于总持股"};
            }

        }
        if (balance < 0) {
            return {'code': 404, 'message': "交易金额大于持仓总额"};
        }else {
            stockPosition.balance = balance;
        }
        return {'code': 200,obj:stockPosition};
    },
    getDetail: function (req, res, next) {
        stockDealDAO.get(req.params.rowId, function (err, result) {
            if (err) {
                next(err, null);
            } else {
                next(null, {knowledge: result.obj});
            }
        });
    },
    deleteByIds: function (req, res, next) {
        var rowIds = req.body.rowIds || [];
        if (rowIds.length > 0) {
            stockGroupDAO.deleteByIds(rowIds, function (err, result) {
                next(err, result);
            });
        } else {
            next();
        }
    }
}